<template>
  <div>
    <el-form :model="spuForm" label-width="100px">
      <el-form-item label="SUP名称">
        <el-input v-model="spuForm.spuName" placeholder="SPU名称"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择品牌">
          <el-option
            v-for="tm in trademarkList"
            :label="tm.tmName"
            :value="tm.id"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SUP描述">
        <el-input
          v-model="spuForm.description"
          placeholder="SPU描述"
          type="textarea"
          rows="4"
        ></el-input>
      </el-form-item>

      <el-form-item label="SUP图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          v-model="supSaleAttrIdName"
          :placeholder="
            unUsedSpuSaleAttrList.length > 0
              ? `还有${unUsedSpuSaleAttrList.length}未选择`
              : `没有了`
          "
        >
          <!-- option不能传递对象，只能传递字符串 -->
          <el-option
            :label="unUsedSpuSaleAttr.name"
            :value="`${unUsedSpuSaleAttr.id}:${unUsedSpuSaleAttr.name}`"
            v-for="unUsedSpuSaleAttr in unUsedSpuSaleAttrList"
            :key="unUsedSpuSaleAttr.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addSaleAttr"
          :disabled="!supSaleAttrIdName"
          >添加销售属性</el-button
        >

        <p />

        <el-table :data="spuForm.spuSaleAttrList" border style="width:100%">
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="spuSaleAttrValue.id"
                v-for="spuSaleAttrValue in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row, tag)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ 添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`你确认删除${row.saleAttrName}吗？`"
                @onConfirm="spuForm.spuSaleAttrList.splice($index, 1)"
              >
                <HintButton
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  title="删除"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <p />

        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data() {
    return {
      spuForm: {
        category3Id: '',
        description: '',
        // 图片可以进行多个文件的上传，图片的参数主要是包括imgName和imgUrl
        spuImageList: [],
        spuName: '',
        // 销售属性列表（表单应该绑定的是下面的spuSaleAttrList)
        spuSaleAttrList: [],
        tmId: 0, // tm->trademark，也就是品牌id,

        spuSaleAttrId: '' // 销售属性绑定的id
      },
      // 上传相关的数据
      dialogImageUrl: '',
      dialogVisible: false,

      trademarkList: [], // 1.获取到所有品牌的列表
      spuImageList: [], // 2. 获取图片列表
      baseSaleAttrList: [], // 3.获取所有spu销售属性列表，通过请求返回来的数据内容
      supSaleAttrIdName: '', // 准备给select进行销售id和name数据的先择用的，最后这个内容要不要放到spuForm表单中去是需要考虑的，所以它可能只是一个临时的过渡对象
      category3Id: ''
    }
  },
  computed: {
    unUsedSpuSaleAttrList() {
      return this.baseSaleAttrList.filter(baseSaleAttr =>
        this.spuForm.spuSaleAttrList.every(
          spuSaleAttr => baseSaleAttr.name !== spuSaleAttr.saleAttrName
        )
      )
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.spuImageList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(response, file, fileList) {
      this.spuImageList = fileList
    },
    // 新增的时候，需要有2个请求操作
    async initAddSpuFormData(category3Id) {
      this.category3Id = category3Id

      const trademarkResult = await this.$API.trademark.getList()

      if (trademarkResult.code === 200) {
        this.trademarkList = trademarkResult.data
      }

      const baseSaleAttrResult = await this.$API.spu.getSaleAttrList()
      if (baseSaleAttrResult.code === 200) {
        this.baseSaleAttrList = baseSaleAttrResult.data
      }
    },
    // 修改的时候，需要有4个请求操作
    async initUpdateSpuFormData(spu) {
      this.category3Id = spu.category3Id

      const result = await this.$API.spu.get(spu.id)
      if (result.code === 200) {
        this.spuForm = result.data
      }

      const imgResult = await this.$API.sku.getSpuImageList(spu.id)
      if (imgResult.code === 200) {
        let spuImageList = imgResult.data

        spuImageList.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl

          return item
        })

        this.spuImageList = spuImageList
      }

      const trademarkResult = await this.$API.trademark.getList()

      if (trademarkResult.code === 200) {
        this.trademarkList = trademarkResult.data
      }

      const baseSaleAttrResult = await this.$API.spu.getSaleAttrList()
      if (baseSaleAttrResult.code === 200) {
        this.baseSaleAttrList = baseSaleAttrResult.data
      }
    },
    // 点击添加销售属性
    addSaleAttr() {
      let [baseSaleAttrId, saleAttrName] = this.supSaleAttrIdName.split(':')
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
      }
      this.spuForm.spuSaleAttrList.push(obj)
      this.supSaleAttrIdName = ''
    },
    // 点击添加属性值，并且切换成input输入框
    showInput(row) {
      this.$set(row, 'inputVisible', true)

      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 添加属性值操作
    handleInputConfirm(row) {
      let saleAttrValueName = row.inputValue
      let baseSaleAttrId = row.baseSaleAttrId

      // 对添加的数据作以一定条件判断
      if (saleAttrValueName.trim() === '') {
        row.inputValue = '' // 设置空的初始值
        return // 中断
      }

      // 重复值的条件判断，不允许出现重复值
      let isRepeat = row.spuSaleAttrValueList.some(
        item => item.saleAttrValueName === saleAttrValueName
      )

      if (isRepeat) {
        this.$message.info('输入的属性值名称不能重复')
        row.inputValue = ''
        return
      }

      // 如果都是成功了的，数据是合理的
      let obj = {
        saleAttrValueName,
        baseSaleAttrId
      }

      // 进行数组的追加操作
      row.spuSaleAttrValueList.push(obj)

      // input框的数据清除
      row.inputValue = ''

      // input框的显示要消失
      row.inputVisible = false
    },
    // 关闭标签
    handleClose(row, tag) {
      row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1)
    },
    // 保存SPU数据
    async save() {
      // 获取收集到的数据
      let { spuForm, spuImageList, category3Id } = this
      // 数据整理
      // 1.图片列表现在已经有的数据与最终需要保存的数据其目标是不一致的
      spuForm.spuImageList = spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data
        }
      })

      // 2. category3Id
      spuForm.category3Id = category3Id

      spuForm.spuSaleAttrList.forEach(item => {
        delete item.inputVisible
        delete item.inputValue
      })

      // 发送请求
      try {
        // 成功
        await this.$API.spu.addUpdate(spuForm)
        // 1.提示信息
        this.$message.success('保存成功')
        // 2.返回上页
        this.$emit('update:visible', false)
        // 3.更新列表，子组件需要通知父组件，也就是spu这个组件，去做数据的操作
        this.$emit('successBack')

        // 4.表单数据的重置，为什么需要重置，因为我们是mvvm，操作表单成功失败以后，数据仍旧保留
        Object.assign(this.$data, this.$options.data())
      } catch (error) {
        // 失败
        this.$message.error('保存失败')
      }
    },
    // 取消回退
    cancel() {
      // 1.控制父组件中的.sync的属性值，确认为false
      this.$emit('update:visible', false)

      // 2.通知父组件，我现在取消
      this.$emit('cancelBack')

      // 3.取消以后数据也需要重置
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>

<style></style>
